package com.cmee.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import lombok.extern.log4j.Log4j2;

@RestController
@Log4j2
public class TestController {

	@Autowired
    private RestTemplate restTemplate;

    @Bean
    @LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
    
//    /**
//     * 运行这个 RestTemplate 不加 @LoadBalanced
//     * @param str
//     * @return
//     */
//    @GetMapping("/echo/{str}")
//    public String echo(@PathVariable String str) {
//        log.info("Discovery");
//        // 通过spring cloud common中的负载均衡接口选取服务提供节点实现接口调用
//        ServiceInstance serviceInstance = loadBalancerClient.choose("server-provider");
//        String url = serviceInstance.getUri() + "/echo/" + str;
//        log.info("url = " + url);
//        return restTemplate.getForObject(url, String.class);
//    }
	
    @GetMapping("/echo/{str}")
    public String echo(@PathVariable String str) {
    	log.info("Discovery");
        return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
    }
}
